package models

import (
	"encoding/json"
	"go.didapinche.com/time"
)

// ApplicationTableName is application table name
const ApplicationTableName = "t_app"

//Application app基本信息表
type Application struct {
	ID           uint64              `gorm:"primary_key,column:id" json:"id,omitempty" form:"id"`
	Name         string              `gorm:"column:name" json:"name,omitempty" form:"name"`
	Description  string              `gorm:"column:description" json:"description,omitempty" form:"description"`
	GitURL       string              `gorm:"column:git_url" json:"git_url,omitempty" form:"git_url"`
	Language     string              `gorm:"column:language" json:"language,omitempty" form:"language"`
	Level        int                 `gorm:"column:level" json:"level,omitempty" form:"level"`
	DevGroupID   string              `gorm:"column:dev_group_id" json:"dev_group_id,omitempty" form:"dev_group_id"`
	DevGroupName string              `gorm:"column:dev_group_name" json:"dev_group_name,omitempty" form:"dev_group_name"`
	QAGroupID    string              `gorm:"column:qa_group_id" json:"qa_group_id,omitempty" form:"qa_group_id"`
	QAGroupName  string              `gorm:"column:qa_group_name" json:"qa_group_name,omitempty" form:"qa_group_name"`
	CreateTime   time.Time           `gorm:"column:create_time" json:"create_time,omitempty" form:"create_time"`
	UpdateTime   time.Time           `gorm:"column:update_time" json:"update_time,omitempty" form:"update_time"`
	Owner        string              `gorm:"column:owner" json:"owner,omitempty" form:"owner"`
	Owners       []*ApplicationOwner `gorm:"-" json:"owners,omitempty" form:"owners"`
	Sla          float64             `json:"sla" gorm:"-"`
	Users        []string            `json:"users" gorm:"-"`
}

// TableName return table name for gorm
func (Application) TableName() string {
	return ApplicationTableName
}

type ApplicationOwner struct {
	UserID   string `gorm:"column:user_id" json:"user_id,omitempty" form:"user_id"`
	UserName string `gorm:"column:user_name" json:"user_name,omitempty" form:"username"`
}

func (app Application) GetOwners() []*ApplicationOwner {
	if app.Owner == "" {
		return nil
	}
	var result []*ApplicationOwner
	err := json.Unmarshal([]byte(app.Owner), &result)
	if err != nil {
		return result
	}
	return result
}

func (app *Application) GetUsers() *Application {
	owner := app.GetOwners()
	for _, u := range owner {
		app.Users = append(app.Users, u.UserName)
	}
	return app
}
